﻿using Microsoft.EntityFrameworkCore;
using Super.Admin.EFCore;
using Super.Admin.Entities;
using Super.Admin.IServices;
using Super.Admin.Utils;

namespace Super.Admin.Services
{
    /// <summary>
    /// 用户管理服务实现类
    /// </summary>
    public class UserService : BaseService, IUserService
    {
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="context">操作的数据库上下文</param>
        public UserService(SuperDataBaseDbContext context) : base(context) { }
        /// <summary>
        /// 获取所有用户列表
        /// </summary>
        /// <returns>用户实体集合</returns>
        public IReadOnlyCollection<UserEntity> GetUsers()
        {
            return Query<UserEntity>(u => true).Include(u => u.UserRoles).ToList();
        }
        /// <summary>
        /// 查询用户列表
        /// </summary>
        /// <param name="userName">用户名</param>
        /// <param name="gender">性别</param>
        /// <param name="nickName">昵称</param>
        /// <param name="phone">手机号</param>
        /// <param name="email">邮箱</param>
        /// <param name="isActive">是否激活</param>
        /// <returns>用户实体集合</returns>
        public IReadOnlyCollection<UserEntity> GetUsers(string userName, int gender, string nickName, string phone, string email, int isActive)
        {
            return Query<UserEntity>(u =>
                (string.IsNullOrEmpty(userName) || u.UserName.Contains(userName)) &&
                (gender == -1 || u.Gender == gender) &&
                (string.IsNullOrEmpty(nickName) || u.NickName.Contains(nickName)) &&
                (string.IsNullOrEmpty(phone) || u.Phone.Contains(phone)) &&
                (string.IsNullOrEmpty(email) || u.Email.Contains(email)) &&
                (isActive == -1 || u.IsActive == isActive)).Include(u => u.UserRoles).ToList();
        }
        /// <summary>
        /// 分页查询用户列表
        /// </summary>
        /// <param name="userName">用户名</param>
        /// <param name="gender">性别</param>
        /// <param name="nickName">昵称</param>
        /// <param name="phone">手机号</param>
        /// <param name="email">邮箱</param>
        /// <param name="isActive">是否激活</param>
        /// <param name="pageSize">一页数量</param>
        /// <param name="pageIndex">页码</param>
        /// <param name="totalCount">总数</param>
        /// <returns>用户实体集合</returns>
        public IReadOnlyCollection<UserEntity> GetUsers(string userName, int gender, string nickName, string phone, string email, int isActive, int pageSize, int pageIndex, out int totalCount)
        {
            PageResult<UserEntity> result = QueryPage<UserEntity, string>(u =>
                 (string.IsNullOrEmpty(userName) || u.UserName.Contains(userName)) &&
                 (gender == -1 || u.Gender == gender) &&
                 (string.IsNullOrEmpty(nickName) || u.NickName.Contains(nickName)) &&
                 (string.IsNullOrEmpty(phone) || u.Phone.Contains(phone)) &&
                 (string.IsNullOrEmpty(email) || u.Email.Contains(email)) &&
                 (isActive == -1 || u.IsActive == isActive),
                 pageSize,
                 pageIndex,
                 x => x.CreateTime,
                 true,
                 q => q.Include(u => u.UserRoles).ThenInclude(ur => ur.Role),
                 q => q.Include(u => u.Department));
            totalCount = result.TotalCount;
            return result.DataList;
        }
        /// <summary>
        /// 登录
        /// </summary>
        /// <param name="userName">用户名</param>
        /// <param name="password">密码</param>
        /// <returns>用户实体</returns>
        public UserEntity Login(string userName, string password)
        {
            if (string.IsNullOrEmpty(userName) || string.IsNullOrEmpty(password))
            {
                throw new ArgumentException("用户名或密码不能为空");
            }
            var user = Query<UserEntity>(u => u.UserName == userName && u.Password == MD5Helper.MD5Encrypt(password) && u.IsActive == 0)
                .Include(u => u.UserRoles)
                .ThenInclude(ur => ur.Role)
                .Include(u => u.Department)
                .ToList().FirstOrDefault();
            if (user == null)
            {
                throw new Exception("用户名或密码错误");
            }
            // 更新最后登录时间
            user.LastLoginTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
            Update<UserEntity>(user);
            return user;
        }
        /// <summary>
        /// 添加用户
        /// </summary>
        /// <param name="userEntity">用户实体</param>
        /// <param name="roleIds">角色ids</param>
        public void CreateUser(UserEntity userEntity, IEnumerable<int> roleIds)
        {
            if (string.IsNullOrEmpty(userEntity.UserName))
            {
                throw new ArgumentException("用户名不能为空");
            }
            var existUser = Query<UserEntity>(u => u.UserName == userEntity.UserName).ToList().FirstOrDefault();
            if (existUser != null)
            {
                throw new Exception($"用户【{userEntity.UserName}】已存在");
            }
            userEntity.UserId = Query<UserEntity>(u => true).ToList().Max(u => u.UserId) + 1;
            userEntity.Password = MD5Helper.MD5Encrypt(userEntity.Password);
            userEntity.CreateTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
            userEntity.UpdateTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
            Insert<UserEntity>(userEntity);
            // 用户角色表插入
            int userId = userEntity.UserId;
            List<UserRoleEntity> insertList = new List<UserRoleEntity>();
            if(roleIds != null)
            {
                foreach (var id in roleIds)
                {
                    UserRoleEntity entity = new UserRoleEntity();
                    entity.RoleId = id;
                    entity.UserId = userId;
                    insertList.Add(entity);
                }
                Insert<UserRoleEntity>(insertList);
            }
            base.Commit(); // 提交事务
        }
        /// <summary>
        /// 修改用户信息
        /// </summary>
        /// <param name="userEntity">用户实体</param>
        /// <param name="roleIds">角色ids</param>
        public void UpdateUser(UserEntity userEntity, IEnumerable<int> roleIds)
        {
            if (string.IsNullOrEmpty(userEntity.UserName))
            {
                throw new ArgumentException("用户名不能为空");
            }
            var existUser = Query<UserEntity>(u => u.UserId == userEntity.UserId).ToList().FirstOrDefault();
            if (existUser == null)
            {
                throw new Exception($"查不到此用户ID【{userEntity.UserId}】");
            }
            existUser = Query<UserEntity>(u => u.UserName == userEntity.UserName && u.UserId != userEntity.UserId).ToList().FirstOrDefault();
            if (existUser != null)
            {
                throw new Exception($"用户【{userEntity.UserName}】已存在");
            }
            userEntity.UpdateTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
            Update<UserEntity>(userEntity);
            if (roleIds != null)
            {
                // 删除用户角色表
                // 用户角色表插入
                List<UserRoleEntity> deleteList = Query<UserRoleEntity>(r => r.UserId == userEntity.UserId).ToList();
                List<object[]> deleteParam = new List<object[]>();
                foreach (var del in deleteList)
                {
                    deleteParam.Add(new object[] { del.UserId, del.RoleId });
                }
                Deletes<UserRoleEntity>(deleteParam);
                List<UserRoleEntity> insertList = new List<UserRoleEntity>();
                foreach (var id in roleIds)
                {
                    UserRoleEntity entity = new UserRoleEntity();
                    entity.RoleId = id;
                    entity.UserId = userEntity.UserId;
                    insertList.Add(entity);
                }
                Insert<UserRoleEntity>(insertList);
            }
            base.Commit(); // 提交事务
        }
        /// <summary>
        /// 修改密码
        /// </summary>
        /// <param name="userEntity">用户实体</param>
        /// <param name="newPassword">角色ids</param>
        public void UpdateUserPassword(UserEntity userEntity, string newPassword)
        {
            // 先查询这个账户是否存在 
            var user = Find<UserEntity>(userEntity.UserId);
            if (!MD5Helper.MD5Verify(userEntity.Password, user.Password))
            {
                throw new Exception("密码错误！！！");
            }
            userEntity.Password = MD5Helper.MD5Encrypt(newPassword);
            Update<UserEntity>(userEntity);
        }
        /// <summary>
        /// 删除用户
        /// </summary>
        /// <param name="userId">用户id</param>
        public void DeleteUser(int userId)
        {
            Delete<UserEntity>(userId);
            base.Commit(); // 提交事务
        }
    }
}
